<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use think\Config;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    public function chexing(){
        $site = Config::get('site');
        $chexing = $site['chexing'];
        return array_flip($chexing);
    }
    public function down_search()
    {
        $param = request()->param();
        $site  = Config::get('site');
        //查询是否有服务止期过期的或者两个月内过期的
//        $one_data = "
//            SELECT id,plan_endtime,status
//            FROM zxcms_list_one
//            WHERE car_vin = '{$param['title']}'
//              AND (status = 7 OR plan_endtime < UNIX_TIMESTAMP(NOW()) OR (plan_endtime > UNIX_TIMESTAMP(NOW()) and plan_endtime <= UNIX_TIMESTAMP(NOW() + INTERVAL 2 MONTH)))
//            ORDER BY id DESC
//            LIMIT 1
//        ";
        $one_data = "
            SELECT id, plan_endtime, status
            FROM zxcms_list_one
            WHERE car_vin = '{$param['title']}'
              AND id = (
                SELECT id
                FROM zxcms_list_one
                WHERE car_vin = '{$param['title']}'
                ORDER BY id DESC
                LIMIT 1
              )
              AND (status = 7
                   OR plan_endtime < UNIX_TIMESTAMP(NOW())
                   OR (plan_endtime > UNIX_TIMESTAMP(NOW()) 
                       AND plan_endtime <= UNIX_TIMESTAMP(NOW() + INTERVAL 2 MONTH)))
       ";
        $list_one = Db::query($one_data);
        if ($list_one) {
            $list_one = $list_one[0];
            //判断时间
            if ($list_one['plan_endtime'] < (86400 * 60 + time()) && $list_one['plan_endtime'] > time()) {
                $list_one['plan_strattime_s'] = date('Y-m-d H:i:s', $list_one['plan_endtime'] + 1);
            }
            if ($list_one['plan_endtime'] < time() || $list_one['status'] == 7) {
                $tomorrow                     = strtotime('tomorrow');           // 获取明天的时间戳
                $formatted_time               = date('Y-m-d H:i:s', $tomorrow);  // 格式化时间
                $list_one['plan_strattime_s'] = $formatted_time;
            }

        }
        $url  = "{$site['apiurl']}index/index/down_search?title={$param['title']}";
        $data = sendCmd($url);
        // dump($url);die;
        return json(['code' => 1, 'msg' => '查询成功', 'data' => $data['data'], 'renew' => $list_one]);

        $data = Db::name('down')
            ->where("car_vin = '{$param['title']}'")
            ->order('id desc')
            ->select();
        foreach ($data as $k => $v) {
            $v['plan_strattime'] = date("Y-m-d H:i:s", strtotime($v['plan_strattime']));
            $v['car_register']   = date("Y-m-d", strtotime($v['car_register']));
            $data[$k]            = $v;
        }
        return json(['code' => 1, 'msg' => '请求成功', 'data' => $data, 'renew' => $list_one]);
    }

    //精友车架号搜索
    public function ceshivin()
    {
        $param = request()->param();

        $site = Config::get('site');
        // $data['vinCode'] = "LS5A2DJW7NA250990";

        $url = "http://jy.niutuwangluo.com/api/index/ceshivin?vinCode={$param['vinCode']}&username=15532153594&password=ac560975bdfeb4e89f31718a408f9a0e114b9709";


        $sendCmd = sendCmd($url);
        if ($sendCmd['status'] == "-1") {
            return json(['code' => -1, 'msg' => $sendCmd['message']]);
        } else {
            return json(['code' => 1, 'msg' => '查询成功', 'data' => $sendCmd['data']]);
        }


    }

    //精友厂牌型号搜索
    public function ceshifgw()
    {
        $param = request()->param();
        $site  = Config::get('site');
        // $data['vinCode'] = "LS5A2DJW7NA250990";

        $url = "http://jy.niutuwangluo.com/api/index/ceshifgw?fgwCode={$param['fgwCode']}&username=15532153594&password=ac560975bdfeb4e89f31718a408f9a0e114b9709";


        $sendCmd = sendCmd($url);
        if ($sendCmd['status'] == "-1") {
            return json(['code' => -1, 'msg' => $sendCmd['message']]);
        } else {
            return json(['code' => 1, 'msg' => '查询成功', 'data' => $sendCmd['data']]);
        }

//        return json($sendCmd);


    }


    //折扣搜索
    public function zhekou()
    {
        $param             = request()->param();
        $param['type'] = preg_replace('/-\d+$/', '', $param['type']);  // 正则表达式去除最后的“-数字”
        $User              = $this->getUser(1);
        $where['zuzhi_id'] = $User['admin']['zuzhi'];
        $where['type']     = $param['type'];
        $listname          = Db::name('zhekou')->where($where)->select();
        if (!$listname) {
            $listname = Db::name('zhekou')->where('zuzhi_id', 1)->where('type', $param['type'])->select();
        }
        $arr = [];
        $i   = 0;
        foreach ($listname as $k => $v) {
            $arr[$i] = $v;
// 			$i++;

            $i++;
        }

        foreach ($listname as $k => $v) {
            $v['ncd'] = $v['ncd'] . '(不含车损)';
            if ($v['no_zhekou']) {
                $v['zhekou'] = $v['no_zhekou'];
            }
            $arr[$i] = $v;
            $i++;
        }
        return json(['code' => 1, 'msg' => '查询成功', 'data' => $arr]);
    }

    public function bili()
    {
        $data     = request()->param();
        $cartype  = $data['cartype'];                         // 假设 cartype 是通过表单提交的
        $cartype2 = $data['cartype2'];                        // 假设 cartype2 是通过表单提交的
        $cartype = preg_replace('/-\d+$/', '', $cartype);  // 正则表达式去除最后的“-数字”
        if ($cartype == '2吨以下' || $cartype == '2吨以下（非营运）') {
            $sf = 0.035;
        } else {
            $sf = 0.035;
            if ($cartype == "网约车") {
                $sf = 0.042;
            }
            if ($cartype == "特二") {
                $sf = 0.04;
            }
            if ($cartype == "货车" || $cartype == "自卸车") {
                if ($cartype2 == "二吨至五吨货车") {
                    if ($cartype == "货车") {
                        $sf = 0.06;
                    }
                    if ($cartype == "自卸车") {
                        $sf = 0.065;
                    }
                } else if ($cartype2 == "五吨至十吨货车") {
                    if ($cartype == "货车") {
                        $sf = 0.04;
                    }
                    if ($cartype == "自卸车") {
                        $sf = 0.065;
                    }
                } else {
                    if ($cartype == "货车") {
                        $sf = 0.03;
                    }
                    if ($cartype == "自卸车") {
                        $sf = 0.055;
                    }
                }
            }
        }
        $sf = 0.035;
        return json(['code' => 1, 'msg' => '查询成功', 'data' => $sf]);
    }

    //实际价值计算
    public function sjjz()
    {
        $data    = request()->param();
        $bili    = 0.009;
        $cartype = $data['cartype'];// 车辆类型
        $cartype = preg_replace('/-\d+$/', '', $cartype);  // 正则表达式去除最后的“-数字”
        if ($cartype == '特二' || $cartype == '货车' || $cartype == '自卸车' || $cartype == '2吨以下' || $cartype == '2吨以下（非营运）' || $cartype == '家庭自用车') {
            $bili = 0.009;
        }
        if ($cartype == '网约车') {
            $bili = 0.011;
        }
        return json(['code' => 1, 'msg' => '查询成功', 'data' => $bili]);
    }

    function accMul($num1, $num2)
    {
        // 这是一个简单的乘法函数，您可以根据需要实现更复杂的逻辑
        return bcmul($num1, $num2, 2);
    }

    public function biao()
    {
        $data = request()->param();
        $data['chexing'] = preg_replace('/-\d+$/', '', $data['chexing']);  // 正则表达式去除最后的“-数字”
//        dump($data);die;
        $datas = [];
        //判断车辆类型
        if ($data['chexing'] == '货车' || $data['chexing'] == '自卸车') {
            //判断几顿一下的
            if ($data['car_leixing'] == '二吨以下货车') {
                $where = ' lei = 3';
            } else if ($data['car_leixing'] == '二吨至五吨货车') {
                $where = ' zi_lei = 1 and lei = 1';
            } else if ($data['car_leixing'] == '五吨至十吨货车') {
                $where = ' zi_lei = 2 and lei = 1';
            } else if ($data['car_leixing'] == '十吨以上货车') {
                $where = ' zi_lei = 3 and lei = 1';
            } else {
                $where = ' zi_lei = 4 and lei = 1';
            }
            //判断是否有第三者
            if ($data['san']['wan']) {
                $field = $this->wan($data['san']['wan']);
                // dump($field);die;
                //判断
                $datas['san'] = Db('list_one_tong')
                    ->where(['type' => 1])
                    ->where($where)
                    ->value($field);
            }
            //判断是否有司机
            if ($data['siji']['wan']) {
                $field         = $this->wan($data['siji']['wan']);
                $datas['siji'] = Db('list_one_tong')
                    ->where(['type' => 2])
                    ->where($where)
                    ->value($field);
            }
            //判断是否有乘客
            if ($data['cheng']['wan']) {
                $field          = $this->wan($data['cheng']['wan']);
                $cheng          = Db('list_one_tong')
                    ->where(['type' => 3])
                    ->where($where)
                    ->value($field);
                $datas['cheng'] = bcmul($cheng, $data['cheng']['num'], 2);
            }
        } else if ($data['chexing'] == '特二') {
            //判断是否有第三者
            if ($data['san']['wan']) {
                $field = $this->wan($data['san']['wan']);
                //判断
                $datas['san'] = Db('list_one_tong')
                    ->where(['lei' => 2, 'type' => 1])
                    ->value($field);
            }
            //判断是否有司机
            if ($data['siji']['wan']) {
                $field         = $this->wan($data['siji']['wan']);
                $datas['siji'] = Db('list_one_tong')
                    ->where(['lei' => 2, 'type' => 2])
                    ->value($field);
            }
            //判断是否有乘客
            if ($data['cheng']['wan']) {
                $field          = $this->wan($data['cheng']['wan']);
                $cheng          = Db('list_one_tong')
                    ->where(['lei' => 2, 'type' => 3])
                    ->value($field);
                $datas['cheng'] = bcmul($cheng, $data['cheng']['num'], 2);
            }
        } else if ($data['chexing'] == '2吨以下') {
            //判断是否有第三者
            if ($data['san']['wan']) {
                $field = $this->wan($data['san']['wan']);
                //判断
                $datas['san'] = Db('list_one_tong')
                    ->where(['lei' => 3, 'type' => 1])
                    ->value($field);
            }
            //判断是否有司机
            if ($data['siji']['wan']) {
                $field         = $this->wan($data['siji']['wan']);
                $datas['siji'] = Db('list_one_tong')
                    ->where(['lei' => 3, 'type' => 2])
                    ->value($field);
            }
            //判断是否有乘客
            if ($data['cheng']['wan']) {
                $field          = $this->wan($data['cheng']['wan']);
                $cheng          = Db('list_one_tong')
                    ->where(['lei' => 3, 'type' => 3])
                    ->value($field);
                $datas['cheng'] = bcmul($cheng, $data['cheng']['num'], 2);
            }
        } else if ($data['chexing'] == '2吨以下（非营运）') {
            //判断是否有第三者
            if ($data['san']['wan']) {
                $field = $this->wan($data['san']['wan']);
                //判断
                $datas['san'] = Db('list_one_tong')
                    ->where(['lei' => 4, 'type' => 1])
                    ->value($field);
            }
            //判断是否有司机
            if ($data['siji']['wan']) {
                $field         = $this->wan($data['siji']['wan']);
                $datas['siji'] = Db('list_one_tong')
                    ->where(['lei' => 4, 'type' => 2])
                    ->value($field);
            }
            //判断是否有乘客
            if ($data['cheng']['wan']) {
                $field          = $this->wan($data['cheng']['wan']);
                $cheng          = Db('list_one_tong')
                    ->where(['lei' => 4, 'type' => 3])
                    ->value($field);
                $datas['cheng'] = bcmul($cheng, $data['cheng']['num'], 2);
            }
        } else if ($data['chexing'] == '网约车') {
            //判断是否有第三者
            if ($data['san']['wan']) {
                $field = $this->wan($data['san']['wan']);
                //判断
                $datas['san'] = Db('list_one_tong')
                    ->where(['lei' => 5, 'type' => 1])
                    ->value($field);
            }
            //判断是否有司机
            if ($data['siji']['wan']) {
                $field         = $this->wan($data['siji']['wan']);
                $datas['siji'] = Db('list_one_tong')
                    ->where(['lei' => 5, 'type' => 2])
                    ->value($field);
            }

            //判断是否有乘客
            if ($data['cheng']['wan']) {

                $field = $this->wan($data['cheng']['wan']);

                $cheng = Db('list_one_tong')
                    ->where(['lei' => 5, 'type' => 3])
                    ->value($field);

                $datas['cheng'] = bcmul($cheng, $data['cheng']['num'], 2);

                // dump($cheng);die;
            }
        } else if ($data['chexing'] == '家庭自用车') {
            //判断是否有第三者
            if ($data['san']['wan']) {
                $field = $this->wan($data['san']['wan']);
                //判断
                $datas['san'] = Db('list_one_tong')
                    ->where(['lei' => 6, 'type' => 1])
                    ->value($field);
            }
            //判断是否有司机
            if ($data['siji']['wan']) {
                $field         = $this->wan($data['siji']['wan']);
                $datas['siji'] = Db('list_one_tong')
                    ->where(['lei' => 6, 'type' => 2])
                    ->value($field);
            }

            //判断是否有乘客
            if ($data['cheng']['wan']) {

                $field = $this->wan($data['cheng']['wan']);

                $cheng = Db('list_one_tong')
                    ->where(['lei' => 6, 'type' => 3])
                    ->value($field);

                $datas['cheng'] = bcmul($cheng, $data['cheng']['num'], 2);

                // dump($cheng);die;
            }
        } else if ($data['chexing'] == '挂车') {
            //判断是否有第三者
            if ($data['san']['wan']) {
                $field = $this->wan($data['san']['wan']);
                //判断
                $datas['san'] = Db('list_one_tong')
                    ->where(['lei' => 1, 'type' => 1, 'zi_lei' => 4])
                    ->value($field);
            }
            //判断是否有司机
            if ($data['siji']['wan']) {
                $field         = $this->wan($data['siji']['wan']);
                $datas['siji'] = Db('list_one_tong')
                    ->where(['lei' => 1, 'type' => 2, 'zi_lei' => 4])
                    ->value($field);
            }

            //判断是否有乘客
            if ($data['cheng']['wan']) {

                $field = $this->wan($data['cheng']['wan']);

                $cheng = Db('list_one_tong')
                    ->where(['lei' => 1, 'type' => 3, 'zi_lei' => 4])
                    ->value($field);

                $datas['cheng'] = bcmul($cheng, $data['cheng']['num'], 2);

                // dump($cheng);die;
            }
        }
        return json(['message' => '成功', 'data' => $datas]);
    }


    //生成支付接口选项
    public function pay_type()
    {
        $param          = request()->param();
        $User           = $this->getUser(1);
        $id = $param['id'];
        $pay_channel_id = Db::name('list_one')->where(['id'=>$id])->where('deletetime',)->value('zhifu');
        if(!$pay_channel_id){
            return json(['code' => -1, 'msg' => '没有支付方式']);
        }
        $data = Db::name('pay_channel')
            ->where(['switch' => 1])
            ->whereIn('id', $pay_channel_id)
            ->where('deletetime', null)
            ->select();

        return json(['code' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 递归获取支付渠道ID
     * @param int $currentId 当前记录ID
     * @return string|null   返回找到的支付渠道ID，若无则返回null
     */
    function getPayChannelId($currentId)
    {
        // 查询当前记录信息
        $row = Db::name('zuzhi')
            ->where(['id' => $currentId])
            ->field('id,pid,pay_channel_id')
            ->find();

        if (!$row) {
            return null; // 记录不存在
        }

        // 若当前记录有支付渠道ID，直接返回
        if (!empty($row['pay_channel_id'])) {
            return $row['pay_channel_id'];
        }

        // 若无上级ID，终止递归
        if (empty($row['pid'])) {
            return null;
        }

        // 递归查询上级
        return $this->getPayChannelId($row['pid']);
    }

    //生成支付二维码
    public function pay_rwm()
    {
        $param    = request()->param();
        $list_one = Db::name('list_one')
            ->where(['id' => $param['id']])
            ->find();
        //判断接口是否正常
        $channel = Db::name('pay_channel')->where(['id' => $param['channel_id'], 'switch' => 1])->where('deletetime', null)->find();
        if (!$channel) {
            return json(['code' => -1, 'msg' => '当前接口无法使用']);
        }
        //生成二维码
        $zhifubao = openssl_encrypt($list_one['id'], 'AES-128-ECB', 'zhifubao', OPENSSL_RAW_DATA);
        $zhifubao = base64_encode($zhifubao);
        $weixin   = openssl_encrypt($list_one['id'], 'AES-128-ECB', 'weixin', OPENSSL_RAW_DATA);
        $weixin   = base64_encode($weixin);
        $zhifubao = str_replace('%', '%25', $zhifubao);
        $zhifubao = str_replace('+', '%2B', $zhifubao);
        $zhifubao = str_replace(' ', '%20', $zhifubao);
        $zhifubao = str_replace('/', '%2F', $zhifubao);
        $zhifubao = str_replace('?', '%3F', $zhifubao);
        $zhifubao = str_replace('#', '%23', $zhifubao);
        $zhifubao = str_replace('&', '%26', $zhifubao);
        $zhifubao = str_replace('=', '%3D', $zhifubao);
        //展示日期
        $time = date('Y-m-d');
        $time = openssl_encrypt($time, 'AES-128-ECB', 'ming', OPENSSL_RAW_DATA);
        $time = base64_encode($time);
        $time = str_replace('%', '%25', $time);
        $time = str_replace('+', '%2B', $time);
        $time = str_replace(' ', '%20', $time);
        $time = str_replace('/', '%2F', $time);
        $time = str_replace('?', '%3F', $time);
        $time = str_replace('#', '%23', $time);
        $time = str_replace('&', '%26', $time);
        $time = str_replace('=', '%3D', $time);
        vendor("phpqrcode.phpqrcode");

        $value = $this->request->scheme() . '://' . $this->request->host() . '/index/index/new_zhifu?id=' . $zhifubao . '&time=' . $time . '&channel_id=' . $param['channel_id'];//二维码内容

        $errorCorrectionLevel = 'L';          //容错级别
        $matrixPointSize      = 5;            //生成图片大小
        $u                    = new \QRcode();
        //生成二维码图片
        ob_start();                           //开启缓冲区
        $QR          = \QRcode::png($value, false, $errorCorrectionLevel, $matrixPointSize, 2);
        $imageString = base64_encode(ob_get_contents());
        ob_end_clean(); //清除缓冲区的内容，并将缓冲区关闭，但不会输出内容

        $list_one['zhifubao'] = $zhifubao;
        $list_one['weixin']   = $weixin;
        $list_one['times']    = date('Y-m-d') . ' 23:59:59';
        $list_one['er']       = "data:image/jpg;base64," . $imageString;

        if ($list_one['jq_price']) {
            $list_one['main_free'] = bcadd(floatval($list_one['jq_price']), floatval($list_one['main_free']), 2);
        }
        if ($list_one['cc_price']) {
            $list_one['main_free'] = bcadd(floatval($list_one['cc_price']), floatval($list_one['main_free']), 2);
        }
        $list_one['channel'] = $channel['name'];
        return json(['code' => 1, 'msg' => '查询成功', 'data' => $list_one]);
    }

    //特别约定
    public function special()
    {
        $arr          = Db::name('special')
            ->where('deletetime', null)
            ->order('sort asc')
            ->select();
        $data['data'] = $arr;
        $data['xc']   = [
            '服务期间内，如发生本服务合同的意外事故造成被服务方损失或者第三方损失的，服务人可选择采取实物补偿的方式承担服务责任。',
            '无其他特别约定。'
        ];
        return json(['code' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    //批文
    public function piwen()
    {
        $data = Db::name('piwen')->where('deletetime', null)->order('sort asc')->select();
        return json(['code' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action     = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename   = $this->request->post("filename");
            $method     = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload     = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload     = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    public function wan($num)
    {
        if ($num == 10000) {
            $field = 'n1';
        }
        if ($num == 20000) {
            $field = 'n2';
        }
        if ($num == 30000) {
            $field = 'n3';
        }
        if ($num == 40000) {
            $field = 'n4';
        }
        if ($num == 50000) {
            $field = 'n5';
        }
        if ($num == 100000) {
            $field = 'n10';
        }
        if ($num == 150000) {
            $field = 'n15';
        }
        if ($num == 200000) {
            $field = 'n20';
        }
        if ($num == 300000) {
            $field = 'n30';
        }
        if ($num == 500000) {
            $field = 'n50';
        }
        if ($num == 1000000) {
            $field = 'n100';
        }
        if ($num == 1500000) {
            $field = 'n150';
        }
        if ($num == 2000000) {
            $field = 'n200';
        }
        if ($num == 3000000) {
            $field = 'n300';
        }
//        dump($num);die;
        return $field;
    }
}
